﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PerfumeShopManagement.DAL;
using PerfumeShopManagement.Model;
using PerfumeShopManagement.Utility;

namespace PerfumeShopManagement.BLL
{
    public class BllProduct : BllAbstractBase<Product, int>
    {
        public BllProduct()
            : base()
        {
            items = DalFactory.ProductDAL.GetAllObjects(); 
        }

        public override List<Product> GetAll()
        {
            return items;
        }

        public override Product Get(int id)
        {
            throw new NotImplementedException();
        }

        public override List<Product> Search(Product criteria)
        {
            return DalFactory.ProductDAL.GetObjectsByCriteria(criteria);
        }

        public override bool Save(Product obj)
        {
            Product product = obj;

            bool updated = false;
            foreach (Product item in items)
            {
                if (item.ProductId == product.ProductId)
                {
                    item.ProductName = product.ProductName;
                    item.DetailInfo = product.DetailInfo;
                    item.Inventory = product.Inventory;
                    item.Price = product.Price;
                    item.CategoryId = product.CategoryId;
                    updated = true;
                    DalFactory.ProductDAL.Update(product);

                    return true;
                }
            }

            if (!updated)
            {
                items.Add(product);
                DalFactory.ProductDAL.Insert(product);

                RepositoryHistory history = new RepositoryHistory();
                history.ProductId = product.ProductId;
                history.ActivityKind = Constants.INITIAL_KIND;
                history.ActiveTime = DateTime.Now;
                history.Value = product.Inventory;
                DalFactory.RepositoryHistoryDAL.Insert(history);

                return true;
            }

            return false;
        }

        public override bool DeleteById(int id)
        {
            if (DalFactory.ProductDAL.DeleteById(id))
            {
                for (int i = items.Count - 1; i >= 0; i--)
                {
                    if (id == items[i].ProductId)
                        items.Remove(items[i]);
                }
                return true;
            }
            return false;
        }
    }
}
